﻿using System;
using System.Collections;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Windows.Forms;

namespace HSIA
{
    public class AmateBussiness
    {
        /// <summary>
        /// 报警语句
        /// Conditions:条件语句
        /// </summary>
        /// <param name="Conditions"></param>
        /// <param name="sDateAera"></param>
        /// <returns></returns>
        public static string vwWarnData(int iType, string Conditions)
        {
            string s = "select dbo.Sensor.*,dbo.GatherData.GatherNo,GatherData.WarnHandleID,dbo.GatherData.WarnType,dbo.GatherData.WarnDelay,dbo.GatherData.T,dbo.GatherData.TW,dbo.GatherData.H,dbo.GatherData.HW,dbo.GatherData.B, aa.WarnName,aa.SensorID,aa.StarTime,aa.WarnTime " +
                        "from({0} {1} {2} {3} {4})aa LEFT OUTER JOIN dbo.Sensor ON aa.SensorID = dbo.Sensor.ID LEFT OUTER JOIN dbo.GatherData ON aa.ID = dbo.GatherData.ID";

            string t = "select a.ID,a.GatherNo,a.SensorID,a.TW,a.HW,a.B,a.WarnName,a.rn-row_number() over(order by a.rn) 'rn' from ({0}) a where ";
            string t1 = "select ID,GatherNo,SensorID,TW,HW,B,WarnHandleID,WarnType,'' WarnName, row_number() over(order by cast(substring(SensorID,charindex('-',SensorID)+1,12) as int),GatherNo) 'rn' from GatherData ";
            t = string.Format(t, t1);

            string tt = "WarnType<>0 and TW>0 and TW<255 " + ((iType == 0) ? "" : "and substring(dbo.Dec2Bin(TW,8)," + iType + ",1)='1' ");

            string s0 = "select min(GatherNo) 'StarTime', max(GatherNo) 'EndTime', datediff(mi,min(GatherNo),max(GatherNo)) 'WarnTime','{1}' WarnName,max(SensorID) 'SensorID',max(ID) 'ID' from({0})t group by rn ";//having datediff(mi,min(GatherNo),max(GatherNo))> '0' "+
            string s2 = (iType == 0 || iType == 6) ? "UNION ALL select GatherNo 'StarTime',GatherNo 'EndTime','' WarnTime,'R' WarnName,SensorID,ID from GatherData where WarnType=0 and TW=256 " + Conditions : "";
            string s3 = (iType == 0 || iType == 7) ? "UNION ALL select GatherNo 'StarTime',GatherNo 'EndTime','' WarnTime,'D' WarnName,SensorID,ID from GatherData where WarnDelay=1 " + Conditions : "";
            string s4 = (iType == 0 || iType == 8) ? "UNION ALL select GatherNo 'StarTime',GatherNo 'EndTime','' WarnTime,'S' WarnName,SensorID,ID from GatherData where WarnType=1 and TW=255" + Conditions : "";

            string sql = string.Format(s,
                string.Format(s0, t + tt + Conditions, "T"),
                string.Format("UNION ALL " + s0, t + "WarnType<>0 and B=0 " + Conditions, "B"),
                s2, s3, s4);
            return sql;
        }

        public static void SetNodeChecked(TreeNode tn, bool blCheck)
        {
            foreach (TreeNode tnChild in tn.Nodes)
            {
                tnChild.Checked = blCheck;
                SetNodeChecked(tnChild, blCheck);
            }
        }

        public static string GetLastGatherNo(DatabaseObject dbo)
        {
            string sRet = "";
            DataTable dt = dbo.GetDataTableBySql("select Value from SystemParam where Name='LastGatherNo'", "aaa");
            if (dt.Rows.Count > 0) sRet = dt.Rows[0][0].ToString();
            return sRet;
        }

        public static int GetMaxTreeLevel(DatabaseObject dbo)
        {
            int iRet = 0;
            DataTable dt = dbo.GetDataTableBySql("select treelevel from area", "aaa");//max(treelevel)
            if (dt.Rows.Count > 0 && dt.Rows[0][0] != DBNull.Value) iRet = Convert.ToInt32(dt.Rows[0][0]);
            return iRet;
        }

        public static void SetGatherNoComboBox(DatabaseObject dbo, ComboBox cbGatherNo)
        {
            DataTable dtGatherNo = dbo.GetDataTableBySql("select top 50 GatherNo from GatherNo order by GatherNo Desc", "GatherNo");
            dtGatherNo.LoadDataRow(new object[] { "" }, true);
            cbGatherNo.DataSource = dtGatherNo;
            cbGatherNo.ValueMember = "GatherNo";
            cbGatherNo.DisplayMember = "GatherNo";
        }

        public static string GetSensorArea(DatabaseObject dbo, string sSensorID, int iWarn)
        {
            DataTable dtSensor = dbo.GetDataTableBySql("select * from Sensor where ID='" + sSensorID + "'", "Sensor");
            if (dtSensor.Rows.Count == 0) return "";
            DataRow drSensor = dtSensor.Rows[0];
            DataTable dtLocationTitle = dbo.GetDataTableBySql("select * from LocationTitle order by FieldIndex", "aaa");
            string sTitle = "";
            float LocationTitle = dtLocationTitle.Rows.Count; //int i = 0;
            foreach (DataRow dr in dtLocationTitle.Rows)
            {
                if (iWarn == 0 && dr["Sounds"].ToString() == "0") continue;
                //if (Math.Round(LocationTitle, 0) + i < dtLocationTitle.Rows.Count) { i++; continue; }
                string sID = dr["ID"].ToString();
                if (drSensor.Table.Columns.IndexOf(sID) > -1)
                {
                    if ((drSensor[sID] != DBNull.Value) && (drSensor[sID].ToString().Trim() != ""))
                    {
                        sTitle = sTitle + " - " + drSensor[sID].ToString().Trim();
                    }
                }
            }
            if (sTitle.StartsWith(" - ")) sTitle = sTitle.Substring(3, sTitle.Length - 3);
            return sTitle;
        }

        public static bool GetSysTimer(DatabaseObject dbo, ref string s0, ref string ss2)
        {
            string sRegister = PublicFunc.sRegister.ToString();
            lock (sRegister)
            {
                bool blRet = false;
                string ss = "";
                string s1 = "";
                string s2 = "";
                string s3 = "";
                string ss3 = "";
                if (PublicFunc.iNetConnect == 0)
                {
                    ss = KeyLog();
                    string[] sl = ss.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    s0 = sl[0];
                    s1 = sl[1];
                    s2 = sl[2];
                    s3 = sl[3];
                }
                else
                {
                    ss = GetSystemParamValue(dbo, "ProductNo", "").ToString();
                    string[] sl = ss.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);
                    s0 = ss;
                    s1 = sl[2];
                    s2 = sl[1];
                    s3 = sl[0];
                }
                ss3 = s3;
                ss2 = GetSystemParamValue(dbo, ss3, "").ToString();
                if (ss2.Trim() != "" || sRegister != "")
                {
                    string sRaw = ss2.Replace("-", "").Replace(" ", "");
                    if (s2.Length < 4) s2 = s2.PadRight(4, 'a'); else s2 = s2.Substring(s2.Length - 4, 4);
                    if (s3.Length < 4) s3 = s3.PadRight(4, 'b'); else s3 = s3.Substring(s3.Length - 4, 4);
                    //if (s3.Length < 8) s3 = s3.PadRight(8, 'a'); else s3 = s3.Substring(s3.Length - 8, 8);
                    string sKey = s2 + s3;
                    sKey = sKey.Remove(6) + "AB";
                    string ss1 = Crypto.SetControl(s1, sKey);
                    if (ss1.StartsWith(sRaw))
                    {
                        if (blRet)
                        {
                            PublicFunc.sRegister = "00000-00000-00000-00000";
                            SetSystemParamValue(dbo, ss3, ss2);
                        }

                        blRet = true;
                    }
                    else
                    {
                        SetSystemParamValue(dbo, "ProductNo", s0);
                        sRaw = sRegister.Replace("-", "").Replace(" ", "");
                        if (ss1.StartsWith(sRaw))
                        {
                            SetSystemParamValue(dbo, ss3, sRegister);
                            blRet = true;
                        }
                    }
                }
                return blRet;
            }
        }

        public static bool GetRegisterClient(DatabaseObject dbo, ref string s0, ref string ss2)
        {
            string sRegister = PublicFunc.sRegister.ToString();
            lock (sRegister)
            {
                bool blRet = false;
                string ss = "";
                string s1 = "";
                string s2 = "";
                string s3 = "";
                string ss3 = "";

                ss = KeyLog();
                string[] sl = ss.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                s0 = sl[0];
                s1 = sl[1];
                s2 = sl[2];
                s3 = sl[3];
                ss3 = s3;

                if (sRegister != "")
                {
                    string sRaw = sRegister.Replace("-", "").Replace(" ", "");
                    if (s2.Length < 4) s2 = s2.PadRight(4, 'a'); else s2 = s2.Substring(s2.Length - 4, 4);
                    if (s3.Length < 4) s3 = s3.PadRight(4, 'b'); else s3 = s3.Substring(s3.Length - 4, 4);
                    //if (s3.Length < 8) s3 = s3.PadRight(8, 'a'); else s3 = s3.Substring(s3.Length - 8, 8);
                    string sKey = s2 + s3;
                    sKey = sKey.Remove(6) + "AB";
                    string ss1 = Crypto.SetControl(s1, sKey);

                    if (ss1.StartsWith(sRaw))
                    {
                        blRet = true;
                    }
                }
                return blRet;
            }
        }

        public static object GetSystemParamValue(DatabaseObject dbo, string sName, object oDefaultValue)
        {
            object oRet = null;
            DataRow drSystemParam = dbo.dtSystemParam.Rows.Find(sName);  //"PosPrintFilter"
            if (drSystemParam != null)// && drSystemParam["Value"].ToString() != ""
            {
                oRet = drSystemParam["Value"];
            }
            else
            {
                dbo.ExcuteSQL("insert into Sys_Param(Name,Value) values('" + sName + "','" + oDefaultValue.ToString() + "')");
                dbo.dtSystemParam.LoadDataRow(new object[] { dbo.dtSystemParam.Rows.Count + 1, sName, oDefaultValue }, true);
                oRet = oDefaultValue;
            }
            return oRet;
        }

        public static void SetSystemParamValue(DatabaseObject dbo, string sName, string sValue)
        {
            DataTable dt = dbo.GetDataTableBySql("select * from Sys_Param where Name='" + sName + "'", "aaa");
            if (dt.Rows.Count == 0)
            {
                dbo.ExcuteSQL("insert into Sys_Param(Name,Value) values('" + sName + "','" + sValue + "')");
            }
            else
            {
                dbo.ExcuteSQL("update Sys_Param set [Value]='" + sValue + "' where Name='" + sName + "'");
            }
            dbo.dtSystemParam.LoadDataRow(new object[] { dbo.dtSystemParam.Rows.Count + 1, sName, sValue }, true);
        }

        public static bool GetSystemParamEnabled(DatabaseObject dbo, string sName)
        {
            object oRet = GetSystemParamValue(dbo, sName, 0);
            return oRet.ToString() == "1";
        }

        public static void SetSystemParamEnabled(DatabaseObject dbo, string sName, bool Enabled)
        {
            SetSystemParamValue(dbo, sName, (!Enabled) ? "0" : "1");
        }

        public void GetLanguage(Form frm)
        {

        }

        public static string GetGatherDate(DatabaseObject dbo, DateTimePicker tpBegin, DateTimePicker tpEnd, int iDIF)
        {
            string sRet = "";
            DateTime dtBegin = tpBegin.Value;
            DateTime dtEnd = tpEnd.Value;
            TimeSpan TSpan = dtEnd - dtBegin;

            if (dtEnd < dtBegin)
            {
                MessageBox.Show(dbo.GetLanguage(99), dbo.GetLanguage(141), MessageBoxButtons.OK, MessageBoxIcon.Information);
                tpBegin.Focus();//"结束日期小于开始日期,请重新调整!", "提示", 
                return "KO";
            }
            else if (iDIF != 0 && TSpan.TotalDays > iDIF)
            {
                MessageBox.Show(string.Format(dbo.GetLanguage(312), iDIF), dbo.GetLanguage(141), MessageBoxButtons.OK, MessageBoxIcon.Information);
                tpEnd.Focus();
                return "KO";
            }
            sRet = PublicFunc.GetUtcOffset(dtBegin, dtEnd);
            return sRet;
        }

        public static string GetDataAvgValue(DatabaseObject dbo, DataTable dtGatherData, int SelectedIndex)
        {
            string sRet = "";
            if (dtGatherData != null && dtGatherData.Rows.Count > 0)
            {
                foreach (DataRow dr in dbo.dtMeasureType.Rows)
                {
                    int iFieldIndex = 0;
                    Int32.TryParse(dr["Tag"].ToString(), out iFieldIndex);
                    iFieldIndex = iFieldIndex + 1;
                    if (iFieldIndex == SelectedIndex || SelectedIndex == 0)
                    {
                        if (dr["Mode"].ToString() == "2") continue;
                        string sNames = " [" + dr["Name"] + "][";
                        string sValue = "";
                        int iCnum = Convert.ToInt32(dr["Cnum"]);
                        double[] iMAXs = new double[iCnum];
                        double[] iMINs = new double[iCnum];
                        double[] iAVGs = new double[iCnum];
                        for (int i = 0; i < iCnum; i++)
                        {
                            string sCnum = (iCnum != 1) ? "_" + (i + 1) : "";
                            string sID = dr["ID"] + sCnum;
                            if (dtGatherData.Columns.IndexOf(sID) == -1) continue;
                            double.TryParse(dtGatherData.Compute("MAX(" + sID + ") ", " ").ToString(), out iMAXs[i]);
                            double.TryParse(dtGatherData.Compute("MIN(" + sID + ") ", " ").ToString(), out iMINs[i]);
                            double.TryParse(dtGatherData.Compute("AVG(" + sID + ") ", " ").ToString(), out iAVGs[i]);
                        }

                        double iMAX = (iCnum > 1) ? iMAXs.Max() : iMAXs[0];
                        double iMIN = (iCnum > 1) ? iMINs.Min() : iMINs[0];
                        double iAVG = (iCnum > 1) ? iAVGs.Average() : iAVGs[0];
                        if (iMAX == 0.0) continue;
                        sValue = sValue + dbo.GetLanguage(315) + ":" + iMAX + dr["Unit"];//最高
                        if (iMIN == 0.0) continue;
                        sValue = sValue + " / " + dbo.GetLanguage(164) + ":" + iMIN + dr["Unit"];//最低
                        if (iAVG == 0.0) continue;
                        sValue = sValue + " / " + dbo.GetLanguage(39) + ":" + iAVG.ToString("0.0") + dr["Unit"];//平均
                        if (sValue != "") sRet = sRet + sNames + sValue + "]";
                    }
                }

            }
            return sRet;
        }

        public static string GetDataAvgInfo(DatabaseObject dbo, DataTable dtGatherData, int SelectedIndex)
        {
            string sRet = "";
            if (dtGatherData != null && dtGatherData.Rows.Count > 0)
            {
                foreach (DataRow dr in dbo.dtMeasureType.Rows)
                {
                    int iFieldIndex = 0;
                    Int32.TryParse(dr["Tag"].ToString(), out iFieldIndex);
                    if (iFieldIndex == SelectedIndex || SelectedIndex == 0)
                    {
                        string sID = dr["ID"].ToString();
                        if (dtGatherData.Columns.IndexOf(sID) == -1 || dr["Mode"].ToString() == "2") continue;
                        string sNames = dr["Name"] + ": ";
                        string sValue = "";

                        object sMAX = dtGatherData.Compute("MAX(" + sID + ") ", " ");
                        if (sMAX == DBNull.Value) continue;
                        sValue = dbo.GetLanguage(315) + sNames + sMAX + dr["Unit"] + "\r ";//最高
                        sValue += Peak(dbo, dtGatherData, sID, sMAX);

                        object sMIN = dtGatherData.Compute("MIN(" + sID + ") ", " ").ToString();
                        if (sMIN == DBNull.Value) continue;
                        sValue += dbo.GetLanguage(164) + sNames + sMIN + dr["Unit"] + "\r ";//最低
                        sValue += Peak(dbo, dtGatherData, sID, sMIN);

                        if (sValue != "") sRet += sValue + "\r ";
                    }
                }

            }
            return sRet;
        }

        public static string Peak(DatabaseObject dbo, DataTable dtGatherDataAll, string Properties, object o)//峰值显示
        {
            string ID = ""; string dL = "";
            DataRow[] drArr = dtGatherDataAll.Select(Properties + "=" + o.ToString());
            DataTable dtNew = dtGatherDataAll.Clone();
            for (int j = 0; j < drArr.Length; j++)
            {
                dtNew.ImportRow(drArr[j]);//ImportRow ;
            }
            int columnsCount = dtNew.Columns.IndexOf("SensorID");
            foreach (DataRow dr in dtNew.Rows)
            {

                if (dr["SensorID"].ToString() == ID) break;
                foreach (DataRow drColumns in dbo.dtLocationTitle.Rows)
                {
                    dL += dr[drColumns["ID"].ToString()].ToString() + " ";
                }
                ID = dr["SensorID"].ToString();
                dL = dL + ID + "(" + dr["GatherNO"].ToString() + ")\r";
            }
            return dL;
        }

        public static void InitPlaceTree(DatabaseObject dbo, TreeView tvArea)
        {
            string strAreaName = "";
            tvArea.Nodes.Clear();
            DataTable dt = dbo.GetDataTableBySql("select * from LocationTitle order by FieldIndex", "aa");
            if (dt.Rows.Count == 0) return;
            strAreaName = dt.Rows[0]["ID"].ToString();

            TreeNode tnRoot = new TreeNode(dbo.GetLanguage(15));//"所有区域"
            tnRoot.Tag = "";
            tnRoot.SelectedImageIndex = tnRoot.ImageIndex = 0;
            tvArea.Nodes.Add(tnRoot);

            string sPlaceSQL = "select distinct {0} AS Name,{1} AS ParentName,{2} AS AllName from Sensor where {0} is not null order by AllName";
            if (dbo.drLoginUser == null) return;
            string strUsersType = dbo.drLoginUser["UserType"].ToString();
            if (strUsersType != "0")
            {
                if (dbo.drLoginUser["AreaName"].ToString() != dbo.GetLanguage(14))
                {
                    sPlaceSQL = "select distinct {0} AS Name,{1} AS ParentName,{2} AS AllName from Sensor where " + strAreaName + "='" + dbo.drLoginUser["AreaName"].ToString() + "' and {0} is not null and {0}<>'' order by AllName";
                }
            }

            string sParentName = "";
            Hashtable ht = new Hashtable();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string sName = CreateTreeNode(dbo, dt.Rows[i], sPlaceSQL, sParentName, ref ht, tnRoot);
                //if (sName == "") continue;
                sParentName = sParentName + "+" + sName;
            }
            tvArea.ExpandAll();
        }

        public static void InitMapTree(DatabaseObject dbo, TreeView tvArea)
        {
            string strAreaName = "";
            tvArea.Nodes.Clear();
            if (dbo.dtLocationTitle.Rows.Count == 0) return;
            strAreaName = dbo.dtLocationTitle.Rows[0]["ID"].ToString();

            TreeNode tnRoot = new TreeNode(dbo.GetLanguage(15));//"所有区域"
            tnRoot.SelectedImageIndex = tnRoot.ImageIndex = 0;
            tnRoot.ToolTipText = tnRoot.Text;
            tnRoot.Tag = "";
            tvArea.Nodes.Add(tnRoot);

            string sPlaceSQL = "select distinct {0} AS Name,{1} AS ParentName,{2} AS AllName from Sensor where {0} is not null order by AllName";
            if (dbo.drLoginUser == null) return;
            string strUsersType = dbo.drLoginUser["UserType"].ToString();
            if (strUsersType != "0")
            {
                if (dbo.drLoginUser["AreaName"].ToString() != dbo.GetLanguage(14))
                {
                    sPlaceSQL = "select distinct {0} AS Name,{1} AS ParentName,{2} AS AllName from Sensor where " + strAreaName + "='" + dbo.drLoginUser["AreaName"].ToString() + "' and {0} is not null and {0}<>'' order by AllName";
                }
            }

            string sParentName = "";
            Hashtable ht = new Hashtable();
            for (int i = 0; i < dbo.dtLocationTitle.Rows.Count; i++)
            {
                if (i != dbo.dtLocationTitle.Rows.Count - 1) continue;
                DataRow dr = dbo.dtLocationTitle.Rows[i];
                dr["FieldIndex"] = 4;
                string sName = CreateTreeNode(dbo, dr, sPlaceSQL, sParentName, ref ht, tnRoot);
                //if (sName == "") continue;
                sParentName = sParentName + "+" + sName;
            }
            tvArea.ExpandAll();
            //tnRoot.Checked = true;
        }

        public static void InitSensorTree(DatabaseObject dbo, TreeView tvArea, Hashtable htSensor)
        {
            string strAreaName = "";
            tvArea.Nodes.Clear();
            DataTable dt = dbo.GetDataTableBySql("select * from LocationTitle order by FieldIndex", "aa");
            if (dt.Rows.Count == 0) return;
            strAreaName = dt.Rows[0]["ID"].ToString();

            TreeNode tnRoot = new TreeNode(dbo.GetLanguage(15));//"所有区域"
            tnRoot.Tag = "";
            tnRoot.Checked = true;
            tnRoot.SelectedImageIndex = tnRoot.ImageIndex = 9;
            tvArea.Nodes.Add(tnRoot);
            string sPlaceSQL = "select distinct {0} AS Name,{1} AS ParentName,{2} AS AllName from Sensor where {0} is not null and {0}<>'' order by AllName";// where {0} is not null and {0}<>'' 

            if (dbo.drLoginUser == null) return;
            string strUsersType = dbo.drLoginUser["UserType"].ToString();
            if (strUsersType != "0")
            {
                if (dbo.drLoginUser["AreaName"].ToString() != dbo.GetLanguage(14))
                {
                    sPlaceSQL = "select distinct {0} AS Name,{1} AS ParentName,{2} AS AllName from Sensor where " + strAreaName + "='" + dbo.drLoginUser["AreaName"].ToString() + "' and {0} is not null and {0}<>'' order by AllName";

                }
            }

            //string sPlaceSQL = "select distinct {0} AS Name,{1} AS ParentName,{2} AS AllName from Sensor where {0} is not null and {0}<>'' order by AllName";// where {0} is not null and {0}<>'' 

            string sParentName = "";
            string sParentCond = "";
            Hashtable ht = new Hashtable();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string sName = CreateTreeSensorNode(dbo, dt.Rows[i], sPlaceSQL, sParentName, ref ht, tnRoot, sParentCond, htSensor);
                //if (sName == "") continue;
                sParentName = sParentName + "+" + sName;
                if (sParentName.StartsWith("+")) sParentName = sParentName.Substring(1, sParentName.Length - 1);
                if (sParentCond == "")
                    sParentCond = " (" + sName + " is not null and " + sName + "<>'') ";
                else
                    sParentCond = sParentCond + " and (" + sName + " is not null and " + sName + "<>'') ";
            }



            string sSensorSQL = "select " + sParentName + " AS ParentName,ID from Sensor where {0} order by ID";//" + sName + " is null or " + sName + "=''
            if (strUsersType != "0")
            {
                if (dbo.drLoginUser["AreaName"].ToString() != dbo.GetLanguage(14))
                {
                    sSensorSQL = "select " + sParentName + " AS ParentName,ID from Sensor where  " + strAreaName + "='" + dbo.drLoginUser["AreaName"].ToString() + "' and  {0} order by ID";//" + sName + " is null or " + sName + "=''
                }
            }


            //if (sParentCond == "") sSensorSQL = string.Format(sSensorSQL, "(" + sName + " is null or " + sName + "='')");
            //else
            sSensorSQL = String.Format(sSensorSQL, sParentCond);
            DataTable dtSensor = dbo.GetDataTableBySql(sSensorSQL, "cc");
            foreach (DataRow drSensor in dtSensor.Rows)
            {
                string sID = drSensor["ID"].ToString();
                TreeNode tnParent = (TreeNode)ht[drSensor["ParentName"].ToString()];
                TreeNode tnSensor = new TreeNode(sID);
                tnSensor.Tag = "*";
                tnSensor.Checked = true;
                tnParent.Nodes.Add(tnSensor);
                if (!htSensor.ContainsKey(sID)) htSensor.Add(sID, tnSensor);
                //if(htsen)
            }
            ht.Clear();
            tvArea.ExpandAll();
        }

        private static string CreateTreeNode(DatabaseObject dbo, DataRow drLocationTitle, string sPlaceSQL, string sParentName, ref Hashtable ht, TreeNode tnRoot)
        {
            Hashtable ht1 = new Hashtable();
            string sName = drLocationTitle["ID"].ToString();
            string sAllName = sParentName + "+" + sName;
            if (sParentName == "") { sParentName = sName; sAllName = sAllName.Substring(1, sAllName.Length - 1); }
            string sSQL = String.Format(sPlaceSQL, sName, sParentName, sAllName);
            DataTable dtPlace = dbo.GetDataTableBySql(sSQL, "bb");
            foreach (DataRow drPlace in dtPlace.Rows)
            {
                string sValue = drPlace["Name"].ToString().Trim();
                if (sValue == "") { continue; }
                TreeNode tn = new TreeNode(sValue);
                TreeNode tnParent = null;
                if (sParentName == sName)
                {
                    tnParent = tnRoot;
                    tn.Tag = sName + "='" + sValue + "'";
                }
                else
                {
                    tnParent = (TreeNode)ht[drPlace["ParentName"].ToString()];
                    if (tnParent == null) continue;
                    tn.Tag = tnParent.Tag + " and " + sName + "='" + sValue + "'";
                }
                tnParent.Nodes.Add(tn);
                tn.SelectedImageIndex = tn.ImageIndex = Convert.ToInt32(drLocationTitle["FieldIndex"]);

                //string sFilter = tnParent.Tag.ToString() + " and " + sName + "='" + sValue;
                //tn.Tag = sFilter;a
                ht1.Add(drPlace["AllName"].ToString(), tn);
            }
            ht = ht1;
            return sName;
        }

        private static string CreateTreeSensorNode(DatabaseObject dbo, DataRow drLocationTitle, string sPlaceSQL, string sParentName, ref Hashtable ht, TreeNode tnRoot, string sParentCond, Hashtable htSensor)
        {
            Hashtable ht1 = new Hashtable();
            string sName = drLocationTitle["ID"].ToString();
            string sAllName = sParentName + "+" + sName; //sAllName = sAllName.Substring(1, sAllName.Length - 1);
            if (sParentName == "") sParentName = sName;
            if (sAllName.StartsWith("+")) sAllName = sAllName.Substring(1, sAllName.Length - 1);
            string sSQL = String.Format(sPlaceSQL, sName, sParentName, sAllName);
            DataTable dtPlace = dbo.GetDataTableBySql(sSQL, "bb");
            TreeNode tnParent = null; TreeNode tnLast = null;
            string sValue = "";
            //if (sParentName == sName) tnParent = tnRoot; else tnParent = (TreeNode)ht[dtPlace.Rows[0]["ParentName"].ToString()];
            foreach (DataRow drPlace in dtPlace.Rows)
            {
                sValue = drPlace["Name"].ToString().Trim();
                TreeNode tn = new TreeNode(sValue);
                if (sParentName == sName)
                {
                    tnParent = tnRoot;
                    tn.Tag = sName + "='" + sValue + "'";
                }
                else
                {
                    tnParent = (TreeNode)ht[drPlace["ParentName"].ToString()];
                    tn.Tag = tnParent.Tag.ToString() + " and " + sName + "='" + sValue + "'";
                }
                tn.Checked = true;
                tnParent.Nodes.Add(tn);
                tn.SelectedImageIndex = tn.ImageIndex = Convert.ToInt32(drLocationTitle["FieldIndex"]);
                tnLast = tnParent;
                if (!ht1.ContainsKey(drPlace["AllName"].ToString()))
                    ht1.Add(drPlace["AllName"].ToString(), tn);
            }
            string sCond = "(" + sName + " is null or " + sName + "='') ";
            string sSensorSQL = "select " + sParentName + " AS ParentName,ID from Sensor where {0} order by ID";//" + sName + " is null or " + sName + "=''
            if (sParentCond == "") sSensorSQL = String.Format(sSensorSQL, sCond);
            else
                sSensorSQL = String.Format(sSensorSQL, sParentCond + " and " + sCond);
            DataTable dtSensor = dbo.GetDataTableBySql(sSensorSQL, "cc");
            foreach (DataRow drSensor in dtSensor.Rows)
            {
                tnParent = (TreeNode)ht[drSensor["ParentName"].ToString()];
                if (tnParent == null) continue;
                string sID = drSensor["ID"].ToString();
                TreeNode tnSensor = new TreeNode(sID);
                tnSensor.Tag = "*";
                tnSensor.Checked = true;
                tnParent.Nodes.Add(tnSensor);
                if (!htSensor.ContainsKey(sID)) htSensor.Add(sID, tnSensor);
            }

            ht = ht1;
            return sName;
        }

        public static void CreateAndFillPlace(DatabaseObject dbo, DataTable dtGatherData)
        {
            int iLevel = dbo.dtLocationTitle.Rows.Count;
            DataTable dtPlace = dbo.GetDataTableBySql("select * from Place where FieldIndex<" + iLevel + " order by FieldIndex", "Place");
            dtPlace.PrimaryKey = new DataColumn[] { dtPlace.Columns["ID"] };
            //string sPlaces = "";
            for (int i = dbo.dtLocationTitle.Rows.Count - 1; i >= 0; i--)
            {
                //sPlaces = sPlaces + "," + "Place" + i;
                dtGatherData.Columns.Add("Place" + i.ToString(), Type.GetType("System.String"));
            }
            FillPlaceData(dtGatherData, dtPlace);
        }

        private static void FillPlaceData(DataTable dtSensor, DataTable dtPlace)//DataTable dtLocationTitle,dtLocationTitle,
        {
            //int iTotelField = dtLocationTitle.Rows.Count;
            foreach (DataRow dr in dtSensor.Rows)
            {
                GetPlaceValue(dr, dr["PlaceID"].ToString(), dtPlace);
            }
        }

        private static void GetPlaceValue(DataRow drSensor, string sPlaceID, DataTable dtPlace)
        {
            DataRow drPlace = dtPlace.Rows.Find(sPlaceID);
            if (drPlace != null)
            {
                drSensor["Place" + drPlace["FieldIndex"].ToString()] = drPlace["Name"];
                if (drPlace["ParentID"] != DBNull.Value)
                    GetPlaceValue(drSensor, drPlace["ParentID"].ToString(), dtPlace);
            }
        }

        public static void FillAreaSensorTreeView(DatabaseObject dbo, TreeView treeView1)
        {
            DataTable dt = dbo.GetDataTableBySql("select count(*) RecCount from LocationTitle ", "Place");
            int iLevel = Convert.ToInt32(dt.Rows[0]["RecCount"]);
            if (iLevel == 0) { treeView1.Nodes.Clear(); return; }
            DataTable dtSensor = dbo.GetDataTableBySql("select ID,PlaceID from Sensor order by ID", "aaa");// where PlaceID in (select ID from Place where PlaceID is null) 
            //dtSensor.PrimaryKey = new DataColumn[] { dtSensor.Columns["ID"]};
            DataTable dtPlace = dbo.GetDataTableBySql("select * from Place where FieldIndex<" + iLevel + " order by FieldIndex", "Place");
            //dtPlace.PrimaryKey = new DataColumn[] { dtPlace.Columns["ID"] };
            treeView1.Nodes.Clear();
            TreeNode tnRoot = new TreeNode("所有区域");// treeView1.Nodes[0];tnRoot
            tnRoot.Checked = true;
            treeView1.Nodes.Add(tnRoot);
            DataRow[] slPlace = dtPlace.Select("ParentID is null");
            tnRoot.Text = tnRoot.Text;// +" ( " + sl.Length + " )";
            //DataRow[] sl = dtPlace.Select("ParentID is null");
            foreach (DataRow dr in slPlace)
            {
                TreeNode tn = new TreeNode(dr["Name"].ToString());
                tnRoot.Nodes.Add(tn);
                tn.Tag = dr["ID"];
                tn.Text = tn.Text;// +" ( " + InitTree(tn, dr["ID"].ToString()) + " ) ";
                InitTree(tn, dr["ID"].ToString(), dtPlace, dtSensor);
                tn.Checked = true;
                DataRow[] slSensor = dtSensor.Select("PlaceID='" + dr["ID"].ToString() + "'");
                foreach (DataRow drSensor in slSensor)
                {
                    TreeNode tnSensor = new TreeNode(drSensor["ID"].ToString());
                    tn.Nodes.Add(tnSensor);
                    //tnSensor.Tag = dr["ID"];
                    tnSensor.Text = drSensor["ID"].ToString();
                    tnSensor.Checked = true;
                }
            }
            treeView1.ExpandAll();
        }

        private static int InitTree(TreeNode tnParent, string sParentID, DataTable dtPlace, DataTable dtSensor)
        {
            //DataTable dtSensor = dbo.GetDataTableBySql("select ID,PlaceID from Sensor order by ID", "aaa");
            DataRow[] sl = dtPlace.Select("ParentID='" + sParentID + "'");
            foreach (DataRow dr in sl)
            {
                TreeNode tn = new TreeNode(dr["Name"].ToString());
                tnParent.Nodes.Add(tn);
                tn.Tag = dr["ID"];
                tn.Text = tn.Text;// +" ( " + InitTree(tn, dr["ID"].ToString()) + " ) ";
                InitTree(tn, dr["ID"].ToString(), dtPlace, dtSensor);
                tn.Checked = true;
                DataRow[] slSensor = dtSensor.Select("PlaceID='" + dr["ID"].ToString() + "'");
                foreach (DataRow drSensor in slSensor)
                {
                    TreeNode tnSensor = new TreeNode(drSensor["ID"].ToString());
                    tn.Nodes.Add(tnSensor);
                    //tnSensor.Tag = dr["ID"];
                    tnSensor.Text = drSensor["ID"].ToString();
                    tnSensor.Checked = true;
                }
            }
            return sl.Length;
        }

        public static void ToXML(DataTable dt, SaveFileDialog saveFileDialog1)
        {
            saveFileDialog1.Filter = "XML files (*.xml)|*.xml";
            saveFileDialog1.FilterIndex = 0;
            saveFileDialog1.RestoreDirectory = true;
            //saveFileDialog1.CreatePrompt = true;
            saveFileDialog1.Title = "Save";
            saveFileDialog1.FileName = null;
            saveFileDialog1.ShowDialog();
            string FileName = saveFileDialog1.FileName;
            if (FileName.Length != 0)
            {
                dt.WriteXml(saveFileDialog1.FileName.ToString());
                MessageBox.Show("数据已经成功导出到:" + saveFileDialog1.FileName.ToString(), "导出完成", MessageBoxButtons.OK, MessageBoxIcon.Information);

            }
        }
        
        public static void ToLog(string sName, string sDate, string sInfo)
        {
            string sHex = "[" + ((sDate != "") ? sDate : PublicFunc.GetUniformDateString(DateTime.Now)) + "]:";
            string sLong = Application.StartupPath + @"\Log\" + sName + ".log";
            try
            {
                if (!Directory.Exists("Log")) Directory.CreateDirectory("Log");
                if (File.Exists(sLong)) sHex += sInfo + "\r\n";
                File.AppendAllText(sLong, sHex);
            }
            catch { }
        }

        public static void ToLog(string sName, string sDate, byte[] byteHex)
        {
            sDate = ((sDate != "") ? sDate : PublicFunc.GetUniformDateString(DateTime.Now));
            string sHex = "";
            string sLong = Application.StartupPath + @"\Log\" + sName + ".log";
            try
            {
                if (!Directory.Exists("Log")) Directory.CreateDirectory("Log");
                if (File.Exists(sLong))
                {
                    foreach (byte b in byteHex) sHex += b.ToString("X2") + "";
                    sHex = "[" + sHex + "]\r\n";
                }
                File.AppendAllText(sLong, sDate + sHex);
            }
            catch { }
        }

        public static string KeyLog()
        {
            string sCPU = ""; string sHDD = ""; string sMac = "";
            string s = PublicFunc.GetHardInfo(ref sCPU, ref sHDD, ref sMac);
            return s + "," + sCPU + "," + sHDD + "," + sMac;
        }

        public static bool isMeasureTypeData(DatabaseObject dbo)
        {
            bool blRet = true;
            DataTable dtMeasureType = dbo.GetDataTableBySql("select Count(*) RecCount from MeasureType", "MeasureType");
            if (Convert.ToInt32(dtMeasureType.Rows[0]["RecCount"]) == 0)
            {
                MessageBox.Show(dbo.GetLanguage(175), dbo.GetLanguage(141), MessageBoxButtons.OK, MessageBoxIcon.Information);
                blRet = false; ;
            }
            return blRet;
        }

        public static bool isDorp(string sGatherNo, double dValue)
        {
            if (sGatherNo == "") return false;
            DateTime time;
            return (DateTime.TryParse(sGatherNo, out time) && (DateTime.Now - time).TotalMinutes < dValue);
        }

        public static string SetStatInfo(DatabaseObject dbo, string sSQL, DataRow drMeasureType, ref double dMin, ref double dMax)
        {
            int iSensorCount = 0;
            int iReceivedCount = 0;
            int iUnReceivedCount = 0;
            //double dMax = 0;
            //double dMin = 0;
            double dAvg = 0;
            int iUpperWarnCount = 0;
            int iLowerWarnCount = 0;

            string sName = drMeasureType["Name"].ToString();
            string sUnit = drMeasureType["Unit"].ToString();
            string sMeasureField = drMeasureType["ID"].ToString();

            string sSQLA = "select count(*) C,MAX({0}) U,MIN({0}) L,AVG({0}) A from vwGatherData where {1}";
            DataTable dt = dbo.GetDataTableBySql(String.Format(sSQLA, sMeasureField, sSQL), "aa");
            if (dt.Rows.Count > 0)
            {
                DataRow dr = dt.Rows[0];
                iSensorCount = Convert.ToInt32(dr["C"]);
                if (iSensorCount > 0)
                {
                    dMax = Convert.ToDouble(dr["U"]);
                    dMin = Convert.ToDouble(dr["L"]);
                    dAvg = Convert.ToDouble(dr["A"]);
                }
                else
                    dMax = dMin = dAvg = 0;
            }
            else
            {
                iSensorCount = 0;
                dMax = dMin = dAvg = 0;
            }
            sSQLA = "select count(*) C from vwGatherData where " + sMeasureField;
            dt = dbo.GetDataTableBySql(sSQLA + " is not null and (" + sSQL + ")", "aa");
            if (dt.Rows.Count > 0)
            {
                iReceivedCount = Convert.ToInt32(dt.Rows[0]["C"]);
                iUnReceivedCount = iSensorCount - iReceivedCount;
            }
            else
            {
                iReceivedCount = iUnReceivedCount = 0;
            }

            //DataRow drLine = dtWarningList.Rows.Find("Temperature");
            //if (drLine != null)
            //{
            dt = dbo.GetDataTableBySql(sSQLA + " >=U" + sMeasureField + " and (" + sSQL + ")", "aa");
            if (dt.Rows.Count > 0)
                iUpperWarnCount = Convert.ToInt32(dt.Rows[0]["C"]);
            //else
            //    iUpperWarnCount = 0;

            dt = dbo.GetDataTableBySql(sSQLA + " <=L" + sMeasureField + " and (" + sSQL + ")", "aa");
            if (dt.Rows.Count > 0)
                iLowerWarnCount = Convert.ToInt32(dt.Rows[0]["C"]);
            //else
            //    iLowerWarnCount = 0;
            //}
            //else
            //{
            //    iUpperWarnCount = 0;
            //    iLowerWarnCount = 0;
            //}
            //"设备数:" + iSensorCount +
            //    " / 有效数据:" + iReceivedCount +
            //    " / 无效数据:" + iUnReceivedCount +
            //    " / 采集率:" + Math.Round((double)iReceivedCount / (double)iSensorCount) * 100 + "% " +
            return " / 最高" + sName + ":" + dMax + sUnit +
             " / 最低" + sName + ":" + dMin + sUnit +
             " / 平均" + sName + ":" + Math.Round(dAvg, 1) + sUnit +
             " / 过高报警:" + iUpperWarnCount +
             " / 过低报警:" + iLowerWarnCount;
        }

        public static string GetStatInfo(DataTable dtGatherData, DataRow drMeasureType, ref double dMin, ref double dMax)
        {
            //int iSensorCount = 0;
            //int iReceivedCount = 0;
            //int iUnReceivedCount = 0;

            double dAvg = 0;
            //int iUpperWarnCount = 0;
            //int iLowerWarnCount = 0;

            string sName = drMeasureType["Name"].ToString();
            string sUnit = drMeasureType["Unit"].ToString();
            string sMeasureField = drMeasureType["ID"].ToString();

            //iSensorCount = dtGatherData.Rows.Count;
            object o = dtGatherData.Compute("max(" + sMeasureField + ")", "");
            if ((o == null) || (o == DBNull.Value)) dMax = 0; else dMax = Convert.ToDouble(o);
            o = dtGatherData.Compute("min(" + sMeasureField + ")", "");
            if ((o == null) || (o == DBNull.Value)) dMin = 0; else dMin = Convert.ToDouble(o);
            o = dtGatherData.Compute("avg(" + sMeasureField + ")", "");
            if ((o == null) || (o == DBNull.Value)) dAvg = 0; else dAvg = Convert.ToDouble(o);

            //DataRow[] sl = dtGatherData.Select(sMeasureField + " >=U" + sMeasureField);
            //iUpperWarnCount = sl.Length;

            //sl = dtGatherData.Select(sMeasureField + " <=L" + sMeasureField);
            //iLowerWarnCount = sl.Length;

            //sl = dtGatherData.Select(sMeasureField + " is not null ");
            //iReceivedCount = sl.Length;

            //iUnReceivedCount = dtGatherData.Rows.Count - iReceivedCount;

            return "采集次数:" + dtGatherData.Rows.Count +
                           " / 最高" + sName + ":" + dMax + sUnit +
                " / 最低" + sName + ":" + dMin + sUnit +
                " / 平均" + sName + ":" + Math.Round(dAvg, 1) + sUnit;
        }

        public static string SetStatInfo(DataTable dtGatherData, DataRow drMeasureType, ref double dMin, ref double dMax)
        {
            int iSensorCount = 0;
            int iReceivedCount = 0;
            int iUnReceivedCount = 0;
            //double dMax = 0;
            //double dMin = 0;
            double dAvg = 0;
            int iUpperWarnCount = 0;
            int iLowerWarnCount = 0;

            string sName = drMeasureType["Name"].ToString();
            string sUnit = drMeasureType["Unit"].ToString();
            string sMeasureField = drMeasureType["ID"].ToString();

            iSensorCount = dtGatherData.Rows.Count;
            object o = dtGatherData.Compute("max(" + sMeasureField + ")", "");
            if ((o == null) || (o == DBNull.Value)) dMax = 0; else dMax = Convert.ToDouble(o);
            o = dtGatherData.Compute("min(" + sMeasureField + ")", "");
            if ((o == null) || (o == DBNull.Value)) dMin = 0; else dMin = Convert.ToDouble(o);
            o = dtGatherData.Compute("avg(" + sMeasureField + ")", "");
            if ((o == null) || (o == DBNull.Value)) dAvg = 0; else dAvg = Convert.ToDouble(o);

            DataRow[] sl = dtGatherData.Select(sMeasureField + " >=U" + sMeasureField);
            iUpperWarnCount = sl.Length;

            sl = dtGatherData.Select(sMeasureField + " <=L" + sMeasureField);
            iLowerWarnCount = sl.Length;

            sl = dtGatherData.Select(sMeasureField + " is not null ");
            iReceivedCount = sl.Length;

            iUnReceivedCount = dtGatherData.Rows.Count - iReceivedCount;

            // "设备数:" + iSensorCount +
            //" / 有效数据:" + iReceivedCount +
            //  " / 无效数据:" + iUnReceivedCount +
            //  " / 采集率:" + Math.Round((double)iReceivedCount / (double)iSensorCount) * 100 + "% " +
            return " / 最高" + sName + ":" + dMax + sUnit +
               " / 最低" + sName + ":" + dMin + sUnit +
               " / 平均" + sName + ":" + Math.Round(dAvg, 1) + sUnit +
               " / 过高报警:" + iUpperWarnCount +
               " / 过低报警:" + iLowerWarnCount;
        }

        public static void FillWarnField(DatabaseObject dbo, DataTable dtMeasureType)
        {
            if (dtMeasureType == null)
                dtMeasureType = dbo.GetDataTableBySql("select * from MeasureType order by Tag", "dtReferSensor");
            string sWarnValue = "";
            //string sCombField = " sensorid+ CONVERT(varchar,GatherDate ,120) ";
            foreach (DataRow dr in dtMeasureType.Rows)
            {
                string sID = dr["ID"].ToString();
                //sMeasureField = sMeasureField + " and (" + sID + "<L" + sID + " or " + sID + " >U" + sID + ")";
                sWarnValue = sWarnValue + "update Sensor set L" + sID + "=" + dr["Lower"].ToString() + " where L" + sID + " is null;";
                sWarnValue = sWarnValue + "update Sensor set U" + sID + "=" + dr["Upper"].ToString() + " where U" + sID + " is null;";
            }
            dbo.ExcuteSQL(sWarnValue);
        }

        public static string WarnType(DatabaseObject dbo, DataTable dtMeasureType)
        {
            string sNames = "";

            string sqRet = "(CASE {1}W {2}' WHEN " + AmateParam.Units.sUReference + " THEN '" + dbo.GetLanguage(249) +
                           "' WHEN " + AmateParam.Units.sLReference + " THEN '" + dbo.GetLanguage(249) +
                           "' ELSE '' END) AS {1}WarnName ";

            foreach (DataRow dr in dtMeasureType.Rows)
            {
                int iWarnType = 0;
                if (int.TryParse(dr["WarnType"].ToString(), out iWarnType) && iWarnType == 0) continue;

                string sName = dr["Name"].ToString();
                int iCnum = Convert.ToInt32(dr["Cnum"]);

                for (int i = 1; i < iCnum + 1; i++)
                {

                    string sCnum = (iCnum != 1) ? "_" + i : "";
                    string sColumn = dr["ID"] + sCnum;
                    string st = "";
                    if (sColumn == "S")
                    {
                        st =
                            String.Format(sqRet, sName.Trim('度'), sColumn,
                                " WHEN 1 THEN '" + dbo.GetLanguage(537) + "' WHEN 2 THEN '" + dbo.GetLanguage(131)) +
                            ",";
                    }
                    else if (sColumn == "B")
                    {
                        st =
                            String.Format(sqRet, sName.Trim('量'), sColumn,
                                " WHEN 4 THEN '" + dbo.GetLanguage(170)) + ",";
                    }
                    else if (sColumn == "D")
                    {
                        st =
                            String.Format(sqRet, dr["Name"], sColumn, " WHEN 4 THEN '" + dr["Name"] + dbo.GetLanguage(470)) +
                            ",";
                    }
                    else
                    {
                        st = String.Format(sqRet, sName.Trim('度'), sColumn,
                            " WHEN " + AmateParam.Units.sAboved + " THEN '" + dbo.GetLanguage(131) +
                            "' WHEN " + AmateParam.Units.sAbove + " THEN '" + dbo.GetLanguage(133) +
                            "' WHEN " + AmateParam.Units.sBelow + " THEN '" + dbo.GetLanguage(167) +
                            "' WHEN " + AmateParam.Units.sBelowd + " THEN '" + dbo.GetLanguage(162)) + ",";
                    }
                    sNames += String.Format(st, sName.Trim('度'));
                }
            }
            return sNames.TrimEnd(',');
        }

        public static string ChartMeasure(DatabaseObject dbo, string sID)
        {
            string sIDs = "";
            DataRow dr = dbo.dtMeasureType.Rows.Find(sID);
            if (dr != null)
            {
                int iCnum = Convert.ToInt32(dr["Cnum"]);
                for (int i = 1; i < iCnum + 1; i++)
                {
                    string sCnum = (iCnum != 1) ? "_" + i : "";
                    string sColumn = sID + sCnum;
                    sIDs += "," + sColumn;
                }
            }
            return sIDs.TrimStart(',');
        }

        public static string vwGatherData(DataTable dtMeasureType)
        {
            string sNames = "";
            foreach (DataRow dr in dtMeasureType.Rows)
            {
                int iCnum = Convert.ToInt32(dr["Cnum"]);
                for (int i = 1; i < iCnum + 1; i++)
                {
                    string sCnum = (iCnum != 1) ? "_" + i : "";
                    string sColumn = dr["ID"] + sCnum;
                    sNames += ",dbo.GatherData." + sColumn;
                    sNames += ",dbo.GatherData." + sColumn + "W";
                }
            }
            return "SELECT dbo.Sensor.*, dbo.GatherData.ID GatherDataID, dbo.GatherData.ReceiverId ReceiverID, dbo.GatherData.SensorID, dbo.GatherData.GatherNo, dbo.GatherData.WarnHandleID, dbo.GatherData.WarnType, dbo.GatherData.X, dbo.GatherData.Y " + sNames + " FROM dbo.GatherData LEFT OUTER JOIN dbo.Sensor ON dbo.GatherData.SensorID = dbo.Sensor.ID ";
        }

        public static void GetMeasureFields(DatabaseObject dbo, DataTable dtMeasureType, ref string sFirstMeasureField, ref string sMeasureFields, ref string sAllMeasureFields, ref string sCompareFields)
        {
            sMeasureFields = ""; sCompareFields = ""; sAllMeasureFields = "";
            if (dtMeasureType == null) dtMeasureType = dbo.GetDataTableBySql("select * from MeasureType order by Tag", "dtReferSensor");
            sFirstMeasureField = dtMeasureType.Rows[0]["ID"].ToString();
            foreach (DataRow dr in dtMeasureType.Rows)
            {
                string sID = dr["ID"].ToString();
                if (sMeasureFields == "") sMeasureFields = sID; else sMeasureFields = sMeasureFields + "," + sID;

                if (sCompareFields == "")
                    sCompareFields = " (" + sID + "<L" + sID + " or " + sID + " >U" + sID + ") ";
                else
                    sCompareFields = sCompareFields + " and (" + sID + "<L" + sID + " or " + sID + " >U" + sID + ") ";

                if (sAllMeasureFields == "")
                    sAllMeasureFields = sID + ",L" + sID + ",U" + sID;
                else
                    sAllMeasureFields = sAllMeasureFields + sID + ",L" + sID + ",U" + sID;
            }
        }

        public static int Register(DatabaseObject dbo, ref int iDay, ref string s, ref string res)
        {
            int iRet = 0;//注册
            if (!GetSysTimer(dbo, ref s, ref res))
            {
                DataTable dt = dbo.GetDataTableBySql("select min(GatherDate) gd from gatherdata", "aaa");
                if (dt.Rows.Count > 0)
                {
                    if (dt.Rows[0]["gd"] != DBNull.Value)
                    {
                        DateTime dtt = Convert.ToDateTime(dt.Rows[0]["gd"]);
                        DateTime dtNow = DateTime.Now;
                        TimeSpan ts = dtNow - dtt;
                        iDay = PublicFunc.iDay - ts.Days;
                        if (iDay <= 0) //过期
                        {
                            iDay = 0;
                            iRet = 2;
                        }
                        else //试用版
                        {
                            iRet = 1;
                        }
                    }
                    else
                    {
                        iRet = 1;
                    }
                }
            }
            return iRet;
        }

        public static void SendMasgeToManager(DatabaseObject dbo, int iMasge, int iParam)
        {
            int iHandle = 0;
            if (int.TryParse(GetSystemParamValue(dbo, "ManagerHandle", "").ToString(), out iHandle))
                PC.SendMessage((IntPtr)iHandle, iMasge, 100, iParam);
        }

        public static void SendMasgeToServer(DatabaseObject dbo, int iMasge, int iParam)
        {
            DataTable dt = dbo.GetDataTableBySql("select * from Sys_Param where Name='ServerHandle'", "aaa");
            if (dt.Rows.Count > 0)
            {
                int iHandle = 0;
                bool bl = int.TryParse(dt.Rows[0]["Value"].ToString(), out iHandle);
                if (bl) PC.SendMessage((IntPtr)iHandle, iMasge, 100, iParam);
            }

        }
    }

    public class BuildColumn
    {
        /// <summary>
        /// 创建表格(sColumnName：绑定数据名称；HeaderText：列名；iWidth：列宽；blSort：此列是否允许筛选) 
        /// </summary>
        /// <returns></returns>
        private static void CreateTextColumn(DataGridView dgv, string sColumnName, string HeaderText, int iWidth, bool blSort)
        {
            DataGridViewTextBoxColumn dcFiex = new DataGridViewTextBoxColumn();
            dcFiex.Name = dcFiex.DataPropertyName = sColumnName;
            dcFiex.HeaderText = HeaderText;
            if (iWidth != 0) dcFiex.Width = iWidth;
            if (!blSort) dcFiex.SortMode = DataGridViewColumnSortMode.NotSortable;
            dgv.Columns.Add(dcFiex);
        }

        private static void CreateTextColumn(DataGridView dgv, string sColumnName, string HeaderText)
        {
            DataGridViewTextBoxColumn dcFiex = new DataGridViewTextBoxColumn();
            dcFiex.Name = dcFiex.DataPropertyName = sColumnName;
            dcFiex.HeaderText = HeaderText;
            dcFiex.SortMode = DataGridViewColumnSortMode.NotSortable;
            dcFiex.AutoSizeMode = DataGridViewAutoSizeColumnMode.Fill;
            dgv.Columns.Add(dcFiex);
        }

        private static void CreateImageColumn(DataGridView dgv, string sColumnName, string HeaderText, int iWidth, bool blSort)
        {
            DataGridViewImageColumn dcFiex = new DataGridViewImageColumn();
            dcFiex.Name = dcFiex.DataPropertyName = sColumnName;
            dcFiex.HeaderText = HeaderText;
            if (iWidth != 0) dcFiex.Width = iWidth;
            if (!blSort) dcFiex.SortMode = DataGridViewColumnSortMode.NotSortable;
            dgv.Columns.Add(dcFiex);
        }

        private static void CreateColumn(DataGridView dgv, string sColumnName, string HeaderText, int iWidth, bool blSort)
        {
            TextAndImageColumn dcFiex = new TextAndImageColumn();
            dcFiex.Name = dcFiex.DataPropertyName = sColumnName;
            dcFiex.HeaderText = HeaderText;
            if (iWidth != 0) dcFiex.Width = iWidth;
            if (!blSort) dcFiex.SortMode = DataGridViewColumnSortMode.NotSortable;
            dgv.Columns.Add(dcFiex);
        }

        private static string CreateTitleColumn(DatabaseObject dbo, DataGridView dgv, bool b)
        {
            string sNames = "";
            if (b)
            {
                foreach (DataRow dr in dbo.dtLocationTitle.Rows)
                {
                    CreateTextColumn(dgv, dr["ID"].ToString(), dr["Name"].ToString(), dr["Name"].ToString().Length * 10, b);
                    sNames = sNames + "," + dr["ID"].ToString();
                }
                foreach (DataRow dr in dbo.dtSensorTitle.Rows)
                {
                    CreateTextColumn(dgv, dr["FieldName"].ToString(), dr["Name"].ToString(),
                        dr["Name"].ToString().Length * 10, b);
                    sNames = sNames + "," + dr["FieldName"].ToString();
                }
            }
            else
            {
                int iCount = 1;
                foreach (DataRow dr in dbo.dtLocationTitle.Rows)
                {
                    if (iCount == dbo.dtLocationTitle.Rows.Count) CreateTextColumn(dgv, dr["ID"].ToString(), dr["Name"].ToString(), dr["Name"].ToString().Length * 50, b);
                    sNames = sNames + "," + dr["ID"].ToString();
                    iCount++;
                }
            }
            return sNames.TrimStart(',');
        }

        private static string CreateMeasureColumn(DatabaseObject dbo, DataGridView dgv, string sStart, string sTag)
        {
            string sNames = "";
            bool bTag = (sTag.Length == 8);
            int j = -1;
            foreach (DataRow dr in dbo.dtMeasureType.Rows)
            {
                if (bTag)
                {
                    int iMTag = 0;
                    if (int.TryParse(dr["Tag"].ToString(), out iMTag) && iMTag > 0)
                    {
                        j++;
                        if (j >= sTag.Length || sTag[j].ToString() != "1") continue;
                    }
                }

                string sColumn = dr["ID"].ToString();
                string sName = dr["Name"].ToString();

                CreateColumn(dgv, sStart + sColumn, sName + "(" + dr["Unit"] + ")", 0, true);

                if (sColumn == "D")
                {
                    sName = sStart + sColumn;
                    sNames += "," + "case when " + sName + "=1 then '" + dbo.GetLanguage(443) + "' when " + sName + "=0 then '" + dbo.GetLanguage(444) + "'else NULL end '" + sName + "'";
                }
                else sNames += "," + sStart + sColumn;
            }
            return sNames;
        }

        private static void ColumnParamIndex(DatabaseObject dbo, DataGridView dgv, string sColumnName, string sNames)
        {
            DataTable dtColumnParam = dbo.GetDataTableBySql("select * from ColumnParam where Name='" + sColumnName + "' order by FieldIndex", "ColumnParam");
            if (dtColumnParam.Rows.Count > 0)
            {
                foreach (DataRow dr in dtColumnParam.Rows)
                {
                    string sFieldName = dr["FieldName"].ToString();
                    if (sNames.IndexOf(sFieldName) > -1)
                    {
                        //if (Convert.ToInt32(dr["FieldIndex"]) >= dgv.Columns.Count) break;
                        DataGridViewColumn dc = dgv.Columns[sFieldName];
                        if (dc == null) continue;

                        try
                        {
                            dc.Width = Convert.ToInt32(dr["FieldWidth"]);
                            dc.DisplayIndex = Convert.ToInt32(dr["FieldIndex"]);
                        }
                        catch { }
                    }
                }
            }
            else
                dbo.ExcuteSQL("delete from ColumnParam where Name='" + sColumnName + "'");
        }

        private static void ColumnFormat(DataGridViewColumn dgvColumn)
        {
            dgvColumn.DefaultCellStyle.Format = PublicFunc.sDateFormat;
        }

        public static string CreatePlaceColumn(DatabaseObject dbo, DataGridView dgv, out Hashtable htFieldList, string sColumnName)
        {
            htFieldList = new Hashtable();
            dgv.Columns.Clear();
            string sNames = "";
            string sCName = "";
            int iWidth = (PublicFunc.sLanguage == "CN") ? 0 : 150;
            //sNames = CreateTitleColumn(dbo, dgv, true);

            foreach (DataRow dr in dbo.dtLocationTitle.Rows)
            {
                sCName = dr["Name"].ToString();
                CreateTextColumn(dgv, dr["ID"].ToString(), sCName, sCName.Length * 10, true);
                htFieldList.Add(sCName, dr["ID"].ToString());
                sNames = sNames + "," + dr["ID"].ToString();
            }
            foreach (DataRow dr in dbo.dtSensorTitle.Rows)
            {
                sCName = dr["Name"].ToString();
                CreateTextColumn(dgv, dr["FieldName"].ToString(), sCName, sCName.Length * 10, true);
                htFieldList.Add(sCName, dr["FieldName"].ToString());
                sNames = sNames + "," + dr["FieldName"].ToString();
            }


            sCName = dbo.GetLanguage(263);//"传感器"
            CreateTextColumn(dgv, "SensorNo", sCName, 0, true);
            htFieldList.Add(sCName, "SensorNo");
            sCName = dbo.GetLanguage(237);//"接收器"
            CreateTextColumn(dgv, "ReceiverId", sCName, 0, true);//"接收器"
            htFieldList.Add(sCName, "ReceiverId");
            sCName = dbo.GetLanguage(250);//"参照器"
            CreateTextColumn(dgv, "ReferSensorID", sCName, 0, true);//"参照器"
            htFieldList.Add(sCName, "ReferSensorID");
            sNames = sNames + ",SensorNo,ReceiverId,ReferSensorID,PlaceID";

            foreach (DataRow dr in dbo.dtMeasureType.Rows)
            {
                int iWarnType = 0;
                if (int.TryParse(dr["WarnType"].ToString(), out iWarnType) && iWarnType == 0) continue;
                string sWarnType = Convert.ToString(iWarnType, 2).PadLeft(4, '0');

                int iCnum = Convert.ToInt32(dr["Cnum"]);
                for (int i = 1; i < iCnum + 1; i++)
                {
                    string sCnum = (iCnum != 1) ? "_" + i : "";
                    string sColumn = dr["ID"] + sCnum;
                    string sCnumName = ((iCnum != 1) ? dbo.GetLanguage(549) + sCnum : "");
                    string sName = dr["Name"].ToString();
                    sCName = "";

                    if (sWarnType[0].ToString() == "1")
                    {
                        sCName = string.Format(dbo.GetLanguage(416), sName) + sCnumName;
                        CreateTextColumn(dgv, "U" + sColumn, sCName, iWidth, true);
                        htFieldList.Add(sCName, "U" + sColumn);
                        sNames += ",U" + sColumn;
                    }
                    if (sWarnType[1].ToString() == "1")
                    {
                        sCName = string.Format(dbo.GetLanguage(417), sName) + sCnumName;
                        CreateTextColumn(dgv, "UP" + sColumn, sCName, iWidth, true);
                        htFieldList.Add(sCName, "UP" + sColumn);
                        sNames += ",UP" + sColumn;
                    }
                    if (sWarnType[2].ToString() == "1")
                    {
                        sCName = string.Format(dbo.GetLanguage(418), sName) + sCnumName;
                        CreateTextColumn(dgv, "LP" + sColumn, sCName, iWidth, true);
                        htFieldList.Add(sCName, "LP" + sColumn);
                        sNames += ",LP" + sColumn;
                    }
                    if (sWarnType[3].ToString() == "1")
                    {
                        sCName = string.Format(dbo.GetLanguage(419), sName) + sCnumName;
                        CreateTextColumn(dgv, "L" + sColumn, sCName, iWidth, true);
                        htFieldList.Add(sCName, "L" + sColumn);
                        sNames += ",L" + sColumn;
                    }
                }

            }

            //CreateTextColumn(dgv, "SS", dbo.GetLanguage(424), 0, true);//"地图标识"
            //sNames = sNames + ",SS";
            //CreateColumn("SBBH", "设备编码", dgv);
            //DataGridViewTextBoxColumn dcSBBH = new DataGridViewTextBoxColumn();
            //dcSBBH.DataPropertyName = "SBBH";
            //dcSBBH.HeaderText = "设备编码";
            //dcSBBH.Name = dcSBBH.DataPropertyName;
            //dgv.Columns.Add(dcSBBH);
            //sNames = sNames + ",SBBH";

            ColumnParamIndex(dbo, dgv, sColumnName, sNames);

            return sNames.TrimStart(',');
        }

        public static string CreateGMapColumn(DatabaseObject dbo, DataGridView dgv, string sColumnName)
        {
            //dgv.Columns.Clear();
            string sNames = "";
            int iWidth = 100;

            sNames = CreateTitleColumn(dbo, dgv, false);

            CreateTextColumn(dgv, "ReceiverId", dbo.GetLanguage(237), iWidth / 2, true);//"传感器"
            CreateTextColumn(dgv, "GatherNo", dbo.GetLanguage(437), 200, true);//"采集批次"
            ColumnFormat(dgv.Columns["GatherNo"]);
            //CreateTextColumn(dgv, "X", dbo.GetLanguage(534), iWidth, false);//"经度"
            //CreateTextColumn(dgv, "Y", dbo.GetLanguage(535), iWidth, false);//"纬度"
            sNames += PublicFunc.GetUtcOffset() + ",ID,ReceiverId,X,Y,W";
            sNames += CreateMeasureColumn(dbo, dgv, "Last", "");
            CreateTextColumn(dgv, "Status", dbo.GetLanguage(481));// "状态"

            ColumnParamIndex(dbo, dgv, sColumnName, sNames);

            return sNames.TrimStart(',');
        }

        public static string CreateQueryManyColumn(DatabaseObject dbo, DataGridView dgv, string sColumnName)
        {
            dgv.Columns.Clear();
            string sNames = "";

            sNames = CreateTitleColumn(dbo, dgv, true);

            CreateTextColumn(dgv, "SensorID", dbo.GetLanguage(263), 0, true);//"传感器"
            CreateTextColumn(dgv, "GatherNo", dbo.GetLanguage(437), 200, true);//"采集批次"
            ColumnFormat(dgv.Columns["GatherNo"]);
            CreateTextColumn(dgv, "ReferSensorID", dbo.GetLanguage(250), 0, true);//"参照器"
            sNames += PublicFunc.GetUtcOffset() + ",ReceiverId,SensorID,ReferSensorID";
            sNames += CreateMeasureColumn(dbo, dgv, "", "");

            ColumnParamIndex(dbo, dgv, sColumnName, sNames);

            return sNames.TrimStart(',');
        }

        public static string CreateQueryOneColumn(DatabaseObject dbo, DataGridView dgv, string sColumnTag, string sColumnName)
        {
            //dgv.Columns.Clear();
            string sNames = "";
            CreateTextColumn(dgv, "GatherNo", dbo.GetLanguage(437), 200, true);//"采集批次"
            ColumnFormat(dgv.Columns["GatherNo"]);
            CreateTextColumn(dgv, "X", dbo.GetLanguage(534), 200, false);//"经度"
            CreateTextColumn(dgv, "Y", dbo.GetLanguage(535), 200, false);//"纬度"
            sNames += PublicFunc.GetUtcOffset() + ",ID,ReceiverId,X,Y,WarnType";
            sNames += CreateMeasureColumn(dbo, dgv, "", sColumnTag);
            return sNames.TrimStart(',');
        }

        public static string CreateWarnColumn(DatabaseObject dbo, DataGridView dgv, string sColumnName, string sMeasureName)
        {
            dgv.Columns.Clear();
            string sNames = "";
            int iWidth = 100;
            //string sMeasureName = "";
            CreateTextColumn(dgv, "GatherNo", dbo.GetLanguage(437), iWidth * 2, true);//"采集批次/采集时间"
            ColumnFormat(dgv.Columns["GatherNo"]);
            CreateTextColumn(dgv, "SensorID", dbo.GetLanguage(263), 0, false);//"传感器"
            sNames += PublicFunc.GetUtcOffset() + ",SensorID,WarnHandleID,WarnType,PlaceID,X,Y";

            sNames += "," + CreateTitleColumn(dbo, dgv, false);

            if (sMeasureName == dbo.GetLanguage(14))
            {
                foreach (DataRow dr in dbo.dtMeasureType.Rows)
                {
                    int iWarnType = 0;
                    if (int.TryParse(dr["WarnType"].ToString(), out iWarnType) && iWarnType == 0) continue;

                    int iCnum = Convert.ToInt32(dr["Cnum"]);
                    for (int i = 1; i < iCnum + 1; i++)
                    {
                        string sCnum = (iCnum != 1) ? "_" + i : "";
                        string sColumn = dr["ID"] + sCnum;
                        string sName = dr["Name"] + ((iCnum != 1) ? "[" + dbo.GetLanguage(549) + sCnum + "]" : "(" + dr["Unit"] + ")");
                        CreateTextColumn(dgv, sColumn, sName, 0, true);
                        sNames += "," + sColumn;
                        CreateTextColumn(dgv, sColumn + "WarnName", dbo.GetLanguage(348) + sCnum, iWidth, true);//"报警类型"
                    }

                    //CreateColumn(dgv, sMeasureName, dbo.GetMeasureName(iType, 3), iWidth, true);
                }
            }
            else
            {
                DataRow dr = dbo.dtMeasureType.Rows.Find(dbo.GetMeasureID("Name", sMeasureName));
                if (dr != null)
                {
                    int iCnum = Convert.ToInt32(dr["Cnum"]);
                    for (int i = 1; i < iCnum + 1; i++)
                    {
                        string sCnum = (iCnum != 1) ? "_" + i : "";
                        string sColumn = dr["ID"] + sCnum;
                        string sName = dr["Name"] +
                                       ((iCnum != 1) ? "[" + dbo.GetLanguage(549) + sCnum + "]"
                                                     : "(" + dr["Unit"] + ")");
                        CreateTextColumn(dgv, sColumn, sName, 0, true);
                        sNames += "," + sColumn;
                        CreateTextColumn(dgv, sColumn + "WarnName", dbo.GetLanguage(348) + sCnum, iWidth, true);
                        //"报警类型"
                    }
                    //CreateColumn(dgv, sMeasureName, dbo.GetMeasureName(iType, 3), iWidth, true);
                }
                else
                {
                    CreateTextColumn(dgv, "WarnName", dbo.GetLanguage(348), iWidth, true);
                }
            }

            ColumnParamIndex(dbo, dgv, sColumnName, sNames);

            return sNames.TrimStart(',');
        }

        //public static string CreateWarnColumn(DatabaseObject dbo, DataGridView dgv, string sColumnName, int iType)
        //{
        //    dgv.Columns.Clear();
        //    string sNames = "";
        //    int iWidth = 100;
        //    CreateTextColumn(dgv, "GatherNo", dbo.GetLanguage(437), iWidth * 2, true);//"采集批次/采集时间"
        //    CreateTextColumn(dgv, "SensorID", dbo.GetLanguage(263), 0, false);//"传感器"
        //    sNames += PublicFunc.GetUtcOffset() + ",SensorID,WarnHandleID,PlaceID";

        //    sNames += "," + CreateTitleColumn(dbo, dgv, false);

        //    if (iType == -1)
        //    {
        //        foreach (DataRow dr in dbo.dtMeasureType.Rows)
        //        {
        //            iType++;

        //            if (Convert.ToInt32(dr["WarnType"]) == 0) continue;

        //            string sColumn = dr["ID"].ToString();
        //            string sName = dr["Name_" + PublicFunc.sLanguage] + "(" + dr["Unit"] + ")";
        //            CreateTextColumn(dgv, sColumn, sName, 0, true);
        //            sNames += "," + sColumn;
        //            CreateTextColumn(dgv, sColumn + "Cnum", dbo.GetLanguage(549), iWidth, true);//"通道"
        //            CreateTextColumn(dgv, sColumn + "WarnName", dbo.GetLanguage(348), iWidth, true);//"报警类型"
        //        }
        //    }
        //    else
        //    {
        //        DataRow dr = dbo.dtMeasureType.Rows[iType];
        //        if (dr != null)
        //        {
        //            string sColumn = dr["ID"].ToString();
        //            string sName = dr["Name_" + PublicFunc.sLanguage] + "(" + dr["Unit"] + ")";
        //            CreateTextColumn(dgv, sColumn, sName, 0, true);
        //            sNames += "," + sColumn;
        //            CreateTextColumn(dgv, sColumn + "Cnum", dbo.GetLanguage(549), iWidth, true);//"通道"
        //            CreateTextColumn(dgv, sColumn + "WarnName", dbo.GetLanguage(348), iWidth, true);//"报警类型"
        //            //CreateColumn(dgv, sMeasureName, dbo.GetMeasureName(iType, 3), iWidth, true);
        //        }
        //        else
        //        {
        //            CreateTextColumn(dgv, "WarnName", dbo.GetLanguage(348), iWidth, true);
        //        }
        //    }

        //    ColumnParamIndex(dbo, dgv, sColumnName, sNames);

        //    return sNames.TrimStart(',');
        //}

        public static string CreateInfo(DatabaseObject dbo, DataGridView dgv, string sStatusName)
        {
            dgv.Columns.Clear();
            string sNames = "";
            int iWidth = 100;
            CreateTextColumn(dgv, "GatherNo", dbo.GetLanguage(491), iWidth * 2, true);//"掉线时间"
            sNames += "," + CreateTitleColumn(dbo, dgv, false);
            CreateTextColumn(dgv, "ID", dbo.GetLanguage(263), 0, false);//"传感器"
            CreateTextColumn(dgv, sStatusName, dbo.GetLanguage(512));
            sNames += PublicFunc.GetUtcOffset() + ",ID,X,Y";

            return sNames.TrimStart(',');
        }

        public static string CreateGatherColumn(DatabaseObject dbo, DataGridView dgv)
        {
            dgv.Columns.Clear();
            string sNames = "";

            CreateTextColumn(dgv, "ReceiverID", dbo.GetLanguage(237), 0, true);//"接受器"
            CreateTextColumn(dgv, "SensorID", dbo.GetLanguage(263), 0, true);//"传感器"
            CreateTextColumn(dgv, "GatherDate", dbo.GetLanguage(437), 200, true);//"采集批次"
            sNames += "GatherDate,SensorID";//PublicFunc.GetUtcOffset() + 
            sNames += CreateMeasureColumn(dbo, dgv, "", "");
            return sNames.TrimStart(',');
        }

        public static void dgv_DataBindingComplete(object sender, DataGridViewBindingCompleteEventArgs e)
        {
            DataGridView dgv = sender as DataGridView;
            if (dgv == null) return;

            int i = 1;
            foreach (DataGridViewRow dvr in dgv.Rows)
            {
                //DataRow dr = (dvr.DataBoundItem as DataRowView).Row;
                TextAndImageCell TICell = null;
                if (dgv.Columns.Contains("B"))
                {
                    TICell = (TextAndImageCell)dvr.Cells["B"];
                }
                else if (dgv.Columns.Contains("LastB"))
                {
                    TICell = (TextAndImageCell)dvr.Cells["LastB"];
                }
                if (TICell != null) TICell.Image = PublicFunc.GetImageFromMeasure(TICell.Value, "B");

                if (dgv.Columns.Contains("Sa"))
                {
                    TICell = (TextAndImageCell)dvr.Cells["Sa"];
                }
                else if (dgv.Columns.Contains("LastSa"))
                {
                    TICell = (TextAndImageCell)dvr.Cells["LastSa"];
                }
                if (TICell != null) TICell.Image = PublicFunc.GetImageFromMeasure(TICell.Value, "Sa");

                if (i % 2 != 0 && dvr.DefaultCellStyle.BackColor != Color.LightGray) dvr.DefaultCellStyle.BackColor = Color.LightGray;
                i++;
            }
        }

        public static void dgv_CellMouseDown(object sender, DataGridViewCellMouseEventArgs e)
        {
            DataGridView dgv = sender as DataGridView;
            if (dgv != null && dgv.SelectedRows.Count == 1 && e.RowIndex >= 0 && e.ColumnIndex >= 0)
            {
                if (e.Button == System.Windows.Forms.MouseButtons.Right)
                {
                    dgv.CurrentCell = dgv.Rows[e.RowIndex].Cells[e.ColumnIndex];
                }
            }
        }

        public static void tv_MouseClick(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
            {
                TreeView tv = sender as TreeView;
                if (tv == null) return;
                TreeNode tn = tv.GetNodeAt(e.X, e.Y);
                tv.SelectedNode = tn;
            }
        }

    }

}
